const glob = require('glob')
const path = require('path')
const Router = require('koa-joi-router')
const Joi = Router.Joi
const apis = ['./src/controller/*.js']
const routes = []

apis.map(pattern => glob.sync(pattern))
    .reduce((previous, current) => previous.concat(current), [])
    .map(relativePath => path.resolve(relativePath))
    .forEach(absolutePath => {
      const module = require(absolutePath)
      const router = Router()
      Object.entries(module).forEach(([key, value]) => {
        if (key === 'prefix') {
          router.prefix(value)
        } else if (typeof value === 'function') {
          const config = { method: 'get', path: '/' }
          const handler = value.call(config, Joi)
          if (handler && !config.handler) {
            config.handler = handler
          }

          if (config.method && config.path && config.handler) {
            router.route(config)
          }
        }
      })
      routes.push(router.middleware())
    })

module.exports = routes